import logging
import transaction

from threading import local
from Shared.DC.ZRDB.TM import TM as _TM, Surrogate

logger = logging.getLogger('enfold.xapian.transaction')

info = logger.info
log_exc = logger.exception
debug = logger.debug

class QueueSavepoint:

    def __init__(self, queue):
        self.queue = queue
        self.state = queue.getQueueState()

    def rollback(self):
        self.queue.setQueueState(self.state)

class QueueTM(_TM, local):

    _registered = 0
    _finalize = 0

    def __init__(self, queue):
        local.__init__(self)
        self.queue = queue

    def _register(self):
        if not self._registered:
            try:
                transaction.get().join(self)
                self._begin()
                self._registered = 1
                self._finalize = 0
            except:
                debug('Oops.')
                log_exc(
                    'Unexpected exception during call to '
                    '_register (registered=%s, finalize=%s)' %
                    (self._registered, self._finalize))


    def savepoint(self):
        return QueueSavepoint(self.queue)

    def _reset(self):
        try:
            self.queue.clearQueue()
        except:
            log_exc('Exception during QueueTM._reset')
        
    def _begin(self):
        self._reset()

    def _abort(self):
        info('Throwing away queue...')
        self._reset()

    def _finish(self):
        try:
            debug('Processing queue...')
            self.queue.processQueue()
            debug('Flushing store...')
            self.queue.flush()
        except:
            log_exc('Exception during QueueTM._finish')
